// SwitchButton.cpp
#include "SwitchButton.h"
#include <QPainter>

SwitchButton::SwitchButton(QWidget *parent)
    : QPushButton(parent), connected(false), offset(0) {
    // 设置断开状态的图标
    QIcon disconnectedIcon;
    disconnectedIcon.addFile(":/icons/disconnected.png"); // 替换为你的O形图标路径
    setIcon(disconnectedIcon);

    // 设置连接状态的图标
    QIcon connectedIcon;
    connectedIcon.addFile(":/icons/connected.png"); // 替换为你的I形图标路径

    // 连接点击信号到槽函数
    connect(this, &QPushButton::clicked, this, &SwitchButton::toggleState);

    // 存储图标
    this->disconnectedIcon = disconnectedIcon;
    this->connectedIcon = connectedIcon;

    // 设置按钮的大小
    setFixedSize(100, 50);
}

int SwitchButton::offset() const {
    return offset;
}

void SwitchButton::setOffset(int value) {
    offset = value;
    update();
}

void SwitchButton::paintEvent(QPaintEvent *event) {
    QPushButton::paintEvent(event);
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);

    // 绘制背景
    painter.setBrush(QBrush(Qt::lightGray));
    painter.setPen(Qt::NoPen);
    painter.drawRoundedRect(rect(), 25, 25);

    // 绘制滑块
    painter.setBrush(QBrush(Qt::white));
    painter.drawRoundedRect(offset, 5, 40, 40, 20, 20);

    // 绘制图标
    QIcon currentIcon = connected ? connectedIcon : disconnectedIcon;
    currentIcon.paint(&painter, offset + 10, 15, 20, 20);
}

void SwitchButton::toggleState() {
    connected = !connected;
    QPropertyAnimation *animation = new QPropertyAnimation(this, "offset");
    animation->setDuration(300);
    animation->setStartValue(offset);
    animation->setEndValue(connected ? 50 : 0);
    animation->start(QAbstractAnimation::DeleteWhenStopped);
}
